package com.newbee.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hhu.newbee.R;
import com.newbee.activity.regist.RegisterActivity;
import com.newbee.activity.tab.ConfigActivity;
import com.newbee.activity.tab.MainActivity;
import com.newbee.app.OnRefrushActivity;
import com.newbee.app.SpeechApp;
import com.newbee.round.CustomImageView;
import com.newbee.service.MainService;
import com.newbee.service.MainServiceTask;
import com.newbee.service.TaskType;
import com.newbee.smack.SmackClient;
import com.newbee.util.StringUtil;

public class LoginActivity extends Activity implements OnClickListener,
		OnRefrushActivity, OnFocusChangeListener
{

	private Button mLogButton;
	private TextView mRegistTextView;
	private EditText mUserAccount;
	private EditText mUserPassword;

	private CustomImageView mhead;

	public static final String ACCOUNT = "ACCOUNT";
	public static final String PASSWORD = "PASSWORD";
	private SmackClient mSmackClient = SmackClient.getInstance();
	public static final String USER_HEAD = "USER_HEAD";
	/********************************/
	public static final String SP_USER_INFO = "USER_INFO";
	public static final String SP_KEY_NICKNAME = "NICKNAME";
	public static final String SP_KEY_EMAIL = "EMAIL";
	public static final String SP_KEY_HEAD = "HEAD";
	public static final String SP_KEY_USERNAME = "SP_KEY_USERNAME";
	/*******************************************/

	public static final String REMBER_ACCOUNT = "REMBER_ACCOUNT";
	public static final String CURRENT_ACCOUNT = "CURRENT_ACCOUNT";
	public static final String CURRENT_PUSSWORD = "CURRENT_PUSSWORD";

	private ProgressDialog mProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_log);

		this.mLogButton = (Button) this.findViewById(R.id.logbtn);
		this.mLogButton.setOnClickListener(this);
		this.mRegistTextView = (TextView) this.findViewById(R.id.register);
		this.mRegistTextView.setOnClickListener(this);
		this.mhead = (CustomImageView) this.findViewById(R.id.log_user_head);
		this.mUserAccount = (EditText) this.findViewById(R.id.account);
		mUserAccount.setOnFocusChangeListener(this);
		this.mUserPassword = (EditText) this.findViewById(R.id.password);
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setTitle("登录");
		mProgressDialog.setCancelable(false);
		mProgressDialog.setMessage("正在登录，请稍等……");
		this.findViewById(R.id.forgentpassword).setOnClickListener(this);
		// SpeechApp.add(this);

		initUserPassword();

	}

	private void initUserPassword()
	{

		SharedPreferences sp = getSharedPreferences(REMBER_ACCOUNT,
				Activity.MODE_MULTI_PROCESS);
		String account = sp.getString(CURRENT_ACCOUNT, null);
		if (account != null)
		{
			mUserAccount.setText(account);
		}
		String password = sp.getString(CURRENT_PUSSWORD, null);
		if (password != null)
		{
			mUserPassword.setText(password);
		}

	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.logbtn:

			String userAccount = this.mUserAccount.getText().toString();
			String userPassword = this.mUserPassword.getText().toString();
			if (userAccount.equals("") || userPassword.equals(""))
			{
				Toast.makeText(this, "账号或密码不能为空！", Toast.LENGTH_LONG).show();
			}
			else if (StringUtil.isEmailFormat(userAccount))
			{
				mProgressDialog.show();
				Map<String, Object> pars = new HashMap<String, Object>();
				pars.put(ACCOUNT, userAccount);
				pars.put(PASSWORD, userPassword);
				MainServiceTask mst = new MainServiceTask(TaskType.USER_LOGIN,
						pars, LoginActivity.class.getName());
				MainService.addActivityMap(LoginActivity.class.getName(), this);
				MainService.addTaskQueue(mst);
			}
			else
			{
				Toast.makeText(this, "邮箱格式不正确", Toast.LENGTH_LONG).show();
			}

			break;
		case R.id.register:
			Intent intent = new Intent(this, RegisterActivity.class);
			startActivity(intent);
			break;

		case R.id.forgentpassword:
		{

			startActivity(new Intent(this, ForgetPassWordActivity.class));
			break;

		}
		default:
			break;
		}

	}

	@Override
	public void init()
	{
		// TODO Auto-generated method stub

	}

	@Override
	public RtInfo refresh(int taskID, Object... paras)
	{

		switch (taskID)
		{
		case TaskType.USER_LOGIN:
			Boolean status = (Boolean) paras[0];

			String nickName = (String) paras[1];
			String head = (String) paras[2];
			String username = (String) paras[3];

			if (status)
			{

				SharedPreferences sp = getSharedPreferences(SP_USER_INFO,
						Activity.MODE_MULTI_PROCESS);
				Editor editor = sp.edit();
				editor.putString(SP_KEY_EMAIL, this.mUserAccount.getText()
						.toString());
				editor.putString(SP_KEY_NICKNAME, nickName);
				editor.putString(SP_KEY_HEAD, head);
				editor.putString(SP_KEY_USERNAME, username);
				editor.commit();
				// user head remember
				sp = getSharedPreferences(USER_HEAD,
						Activity.MODE_MULTI_PROCESS);

				editor = sp.edit();
				editor.putString(this.mUserAccount.getText().toString(), head);
				editor.commit();
				// remember password
				sp = getSharedPreferences(REMBER_ACCOUNT,
						Activity.MODE_MULTI_PROCESS);
				editor = sp.edit();
				editor.putString(CURRENT_ACCOUNT, this.mUserAccount.getText()
						.toString());
				editor.putString(CURRENT_PUSSWORD, this.mUserPassword.getText()
						.toString());
				editor.commit();
				mProgressDialog.hide();
				// Intent intent = new Intent(this, MainActivity.class);
				// startActivity(intent);
				
				//设置用户状态，表示用户已经登录
				sp = this.getSharedPreferences(
						MainActivity.SP_USR_LOGIN_STATUS,
						Activity.MODE_MULTI_PROCESS);
				editor = sp.edit();
				editor.putBoolean(MainActivity.LOGIN_STATUE, true);
				editor.apply();
				this.finish();
			}
			else
			{
				Toast.makeText(this, "账号或者密码不正确！", Toast.LENGTH_LONG).show();
				mProgressDialog.hide();
			}
			break;

		default:
			break;
		}
		return null;

	}

	@Override
	protected void onDestroy()
	{
		MainService.removeActivity(LoginActivity.class.getName());
		
		mProgressDialog.dismiss();
		SmackClient.getInstance().initAddFriendListener();
		super.onDestroy();
	}

	@Override
	public void onFocusChange(View v, boolean isget)
	{
		switch (v.getId())
		{
		case R.id.account:
		{

			// 失去焦点是代码
			SharedPreferences sp = getSharedPreferences(USER_HEAD,
					Activity.MODE_MULTI_PROCESS);
			String head = sp.getString(this.mUserAccount.getText().toString(),
					null);
			if (head != null)
			{

				File file = new File(Environment.getExternalStorageDirectory()
						+ SpeechApp.HEAD_FILE + "/" + head + ".png");
				if (file.exists())
				{
					try
					{
						FileInputStream fis = new FileInputStream(file);
						Bitmap headBitMap = BitmapFactory.decodeStream(fis);
						mhead.setmSrc(headBitMap);
						mhead.invalidate();
						// headBitMap.recycle();
						fis.close();
					}
					catch (FileNotFoundException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

			}
			break;
		}

		default:
			break;
		}

	}

	public boolean onKeyDown(int keyCode, KeyEvent event)
	{

		// if (keyCode == KeyEvent.KEYCODE_BACK)
		// {
		//
		// SpeechApp.exit();
		// return true;
		// }
		return super.onKeyDown(keyCode, event);
	}

}
